package com.yuan.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProcessTool {

	private static final Logger log = LoggerFactory.getLogger(ProcessTool.class);
	
	public static int exec(String cmdText, StringBuilder result, String charset) throws UnsupportedEncodingException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		int exitValue = exec(cmdText, baos);
		result.append(new String(baos.toByteArray(), charset));
		
		return exitValue;
	}
	
	public static int exec(String cmdText, OutputStream os){
		String[] cmds = cmdText.split(" ");
		
		ProcessBuilder proc = new ProcessBuilder(Arrays.asList(cmds));
		proc.redirectErrorStream(true);
		int exitValue = 0;
		try {
			Process process = proc.start();
			if(os != null){
				if(process.getInputStream() != null){
					StreamUtil.output(process.getInputStream(), os, true, false);
				}
			}
			exitValue = process.waitFor();
		}catch (Exception e) {
			log.warn(e.getMessage(), e);
		}
		
		return exitValue;
	}
	
	public static String getCommandResult(String cmdText, String charset) throws UnsupportedEncodingException{
		StringBuilder sb = new StringBuilder();
		exec(cmdText, sb, charset);
		return sb.toString();
	}
	
	public static void cmd(String command){
		cmd(command, false, new OutputStreamWriter(System.out));
	}
	public static void cmd(String command, boolean tty){
		cmd(command, tty, new OutputStreamWriter(System.out));
	}
	public static void cmd(String command, boolean tty, Writer out){
		Process process = null;
		try{
			if(tty){// 为命令启用tty, 命令中包含管道,重定向时需要 
				String[] cmd = {"/bin/sh", "-c", command};
				process = Runtime.getRuntime().exec(cmd);
			}else{
				process = Runtime.getRuntime().exec(command);
			}
			outputResult(process, out);
			process.waitFor();
		}catch(Exception e){
			e.printStackTrace();
			if(process != null) process.destroy();
		}
	}
	
	private static void outputResult(Process process, Writer out)throws IOException{
    	if(process.getErrorStream() != null){
    		StreamUtil.output(new InputStreamReader(process.getErrorStream(), "UTF-8"), out, true, false);
		}
		if(process.getInputStream() != null){
			StreamUtil.output(new InputStreamReader(process.getInputStream(), "UTF-8"), out, true, false);
		}
    }
	
	public static void main(String[] args)throws Exception{
//		System.out.println(getCommandResult("ipconfig /all", "GBK"));
//		System.out.println(getCommandResult("netstat -a", "GBK"));
//		exec("netstat -a", System.out);
		cmd("ls");
	}
	
}
